import threading

import waitress

from future_fields import FutureField

app_field = FutureField("app")

from .factory import create_app
from config import Config
from .task import TaskManager

app = create_app()

app_field.set(app)

from .view import *
from .error_handlers import *

class Server:
    """
    管理api服务器。
    """
    def __init__(self) -> None:
        self.ip = ""
        self.port = 0
        self.debug = False

    def init(self, config:Config) -> None:
        config.define_key("api_ip", "0.0.0.0") \
              .define_key("api_port", 8544) \
              .define_key("api_debug", False)
        
    def config(self, config:dict) -> None:
        self.ip = config["api_ip"]
        self.port = config["api_port"]
        self.debug = config["api_debug"]

    def run(self, task_manager:TaskManager, thread:bool=False) -> None:
        """
        app run xd
        """
        app.task_manager = task_manager
        print("Serving Yan Service on {host}:{port}".format(host=self.ip, port=self.port))
        if thread:
            threading.Thread(
                target = waitress.serve,
                kwargs= {
                    "app": app,
                    "host": self.ip,
                    "port": self.port
                }
            )
        else:
            waitress.serve(app, host=self.ip, port=self.port)